package com.core.config.filter;

import com.core.system.service.ISystemUserService;
import com.core.system.utils.SecurityUser;
import com.pojo.entity.SystemUserEntity;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.Objects;

/**
 *  用户验证过滤器
 * @author Huawei
 * @date 2023-10-23 15:36
 */

@WebFilter(filterName = "authFilter", urlPatterns = "/*")
@Order(value = 1)
public class AuthFilter implements Filter {
    @Resource
    public ISystemUserService userService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SystemUserEntity user = userService.getUser(authentication.getName());
        if (!Objects.isNull(user)) {
            SecurityUser.setUser(user);
            chain.doFilter(request, response);
            return;
        }
        response.getWriter().write("未登录或登录已过期");
    }

}
